package com.kw.admin.config;


import com.kw.common.core.util.SpringContextHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @author new
 * <p>
 * WebSocket配置类
 */
//js方法
	//  import * as SockJS from 'sockjs-client'
//  connection() {
//		  const token = store.getters.access_token
//		  const TENANT_ID = getStore({name: 'tenantId'}) ? getStore({name: 'tenantId'}) : '1'
//		  const headers = {
//		  'Authorization': 'Bearer ' + token
//		  }
//		  // 建立连接对象
//		  this.socket = new SockJS('http://localhost:9000/gateway/system-server/ws')// 连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息
//		  // 获取STOMP子协议的客户端对象
//		  this.stompClient = Stomp.over(this.socket)
//		  this.stompClient.debug = null
//		  // 向服务器发起websocket连接
//		  this.stompClient.connect(headers, () => {
//		  this.stompClient.subscribe('/task/' + this.userInfo.username  + '/remind', (msg) => { // 订阅服务端提供的某个topic;
//		  this.$notify({
//		  title: '协同提醒',
//		  type: 'warning',
//		  dangerouslyUseHTMLString: true,
//		  message: msg.body + '任务，请及时处理',
//		  offset: 60
//		  })
//		  })
//		  }, (err) => {
//
//		  })
//		  },

@Slf4j
@Configuration
@AllArgsConstructor
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
	@Autowired
	private DefaultTokenServices defaultTokenServices;
	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/ws")
				.setAllowedOrigins("*")
				.withSockJS();
	}

	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		registry.setUserDestinationPrefix("/task/");
	}




	@Override
	public void configureClientInboundChannel(ChannelRegistration registration) {
		registration.interceptors(new ChannelInterceptor() {
			@Override
			public Message<?> preSend(Message<?> message, MessageChannel channel) {
				StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
				// 判断是否首次连接请求
				if (StompCommand.CONNECT.equals(accessor.getCommand())) {
					String tokens = accessor.getFirstNativeHeader("Authorization");

					log.info("webSocket token is {}", tokens);
					if (StringUtils.isBlank(tokens)) {
						return null;
					}
					log.info("console {}", message.getPayload());
					//有bug？？？？？？userInfoTokenServices的 oAuth2RestTemplate需要new出来 而不是用工厂 不然没有OAuth2ClientContext
					//remoteTokenService和jwt本地就不存在这个问题
					OAuth2Authentication auth2Authentication = defaultTokenServices.loadAuthentication(tokens.split(" ")[1]);
					if (auth2Authentication != null) {
						SecurityContextHolder.getContext().setAuthentication(auth2Authentication);
						accessor.setUser(() -> auth2Authentication.getName());
						return message;
					}else{

						return  null;
					}
				}
					//不是首次连接，已经成功登陆
					return message;
				}

		});
	}
}
